package cn.aigoubuy.web.servelt;

import cn.aigoubuy.domain.*;
import cn.aigoubuy.service.OrderService;
import cn.aigoubuy.service.impl.OrderServiceImpl;
import cn.aigoubuy.utils.AppPayConfig;
import cn.aigoubuy.utils.UUIDUtils;
import cn.aigoubuy.web.base.BaseServlet;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@WebServlet("/orderServlet")
public class OrderServlet extends BaseServlet {
    /**
     * 生成订单 将购物车中的信息以订单的形式保存
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String saveOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.获得数据
        // 1.1 获得登录用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            request.setAttribute("msg", "请登录之后在下单");
            return "/jsp/login.jsp";
        }
        // 1.2 获得购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        // 2.创建Order对象，封装数据
        Order order = new Order();
        // 2.1 服务器自动生成
        order.setOid(UUIDUtils.getCode());
        order.setState(1); // 未付款
        order.setOrdertime(new Date());
        // 2.2 设置总金额
        order.setTotal(cart.getTotal());
        // 2.3 设置所属的用户
        order.setUser(loginUser);
        // 2.4 设置订单项的集合
        // 遍历购物项的同时,创建订单项,为订单项赋值
        for (CartItem item : cart.getCartItems()) {
            // 将购物项中的数据 抓换到 订单详情对象
            OrderItem orderItem = new OrderItem();
            orderItem.setItemid(UUIDUtils.getCode());
            orderItem.setQuantity(item.getNum());
            orderItem.setSubtotal(item.getSubTotal());
            orderItem.setProduct(item.getProduct());
            //设置当前的订单项属于哪个订单:程序的角度体检订单项和订单对应关系
            orderItem.setOrder(order);
            order.getList().add(orderItem);
        }
        // 2.5 调用业务层功能:保存订单
        OrderService orderService = new OrderServiceImpl();
        //将订单数据,用户的数据,订单下所有的订单项都传递到了service层
        orderService.saveOrder(order);
        // 2.6 清空购物车
        cart.clearCart();
        // 将订单放入request
        request.setAttribute("order", order);
        // 2.7 页面跳转
        return "/jsp/order_info.jsp";
    }
    /**
     * 我的订单
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String findByUid(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 1.1 获取当前页
        int pageNum = 1;
        try {
            String pageNumStr = request.getParameter("num");
            if(pageNumStr != null && !"".equals(pageNumStr)) {
                pageNum = Integer.parseInt(pageNumStr);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        int pageSize = 3; //暂时固定值
        // 1.2 获得当前用户
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        // 2.通过业务层查询
        OrderService orderService = new OrderServiceImpl();
        PageBean<Order> pageBean = orderService.findByUid(loginUser,pageNum,pageSize);
        // 3.将数据放入到request域中
        request.setAttribute("page",pageBean);
        return "/jsp/order_list.jsp";
    }

    /**
     * 通过订单id查询详情
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String findByOid(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 1.获取到订单oid
        String oid=request.getParameter("oid");
        // 2.调用业务层功能:根据订单编号查询订单信息
        OrderService OrderService=new OrderServiceImpl();
        Order order=OrderService.findByOid(oid);
        // 3.将订单放入request
        request.setAttribute("order", order);
        // 4.转发到/jsp/order_info.jsp
        return "/jsp/order_info.jsp";
    }

    /**
     * 支付订单
     * @param request
     * @param response
     * @throws Exception
     */
    public void payOrder(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //1.获取请求参数
        final String oid = request.getParameter("oid");
        final String name = request.getParameter("name");
        final String address = request.getParameter("address");
        final String telephone = request.getParameter("telephone");
        final String pd_FrpId = request.getParameter("pd_FrpId");
        //2.调用业务层，查询订单
        OrderService orderService = new OrderServiceImpl();
        final Order order = orderService.findByOid(oid);
        order.setAddress(address);
        order.setTelephone(telephone);
        order.setName(name);
        orderService.update(order);
        // 3.整合支付
        // byte[] serialize = SerializeUtil.serialize(orderIds);
        //redisServer.setCacheValueForTime(uuid,serialize,1000*60*60*30);
        //获得初始化的AlipayClient,将上面创建的配置类中的变量设置到该对象中
        AlipayClient alipayClient = new
                DefaultAlipayClient(AppPayConfig.gatewayUrl, AppPayConfig.app_id,
                AppPayConfig.merchant_private_key, "json", AppPayConfig.charset,
                AppPayConfig.alipay_public_key, AppPayConfig.singn_type);
        //设置请求参数,并把配置类中的两个路径设置进去
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AppPayConfig.return_url);
        alipayRequest.setNotifyUrl(AppPayConfig.notify_url);
        //如果想正常调用接口则需要传一些必要参数,out_trade_no:订单号,保证唯一性,支付宝根据该参数生成你的支付单号,
        // total_amount:需要支付的金额,注意是String型,且金额计数的分割","不能存在(例如1,000就是错误的参数),
        // subject:对物品进行描述,product_code:是支付类型.更多详细的参数信息参考链接:
        // [https://docs.open.alipay.com/api_1/alipay.trade.page.pay]
        // (https://docs.open.alipay.com/api_1/alipay.trade.page.pay)
        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\""+oid +"\","
                    + "\"total_amount\":\""+order.getTotal() +"\","
                    + "\"subject\":\""+ "测试支付" +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result;
            //发送请求并返回
            result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println("*********************\n返回结果为："+result);
            response.setContentType("text/html;charset=" + AppPayConfig.charset);
            response.getWriter().write(result);
            response.getWriter().flush();
            response.getWriter().close();
        // return JSON.toJSONString(result);
        // return null;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // return null;
        }
    }

    public void callBackSuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //可以根据request.getParameterMap()获得到调用接口时传递的一些参数去做后续的业务处理
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] out_trade_nos = parameterMap.get("out_trade_no");
/*        String[] total_amount = parameterMap.get("total_amount");
        String[] name = parameterMap.get("name");
        String[] address = parameterMap.get("address");
        String[] telephone = parameterMap.get("telephone");*/
        String oid = out_trade_nos[0];
        //如果支付成功,更新订单状态
        //OrderService orderService=new OrderServiceImpl();
        //Order order=orderService.findByOid(oid);
        //order.setState(2);
        OrderService orderService = new OrderServiceImpl();
        final Order order = orderService.findByOid(oid);
        order.setState(2);
/*        order.setTotal(NumberUtils.toDouble(total_amount[0]));
        order.setName(name[0]);
        order.setAddress(address[0]);
        order.setTelephone(telephone[0]);*/
        orderService.update(order);

        //向request放入提示信 息
        request.getSession().setAttribute("msg", "支付成功！订单号：" + oid + "金额：" + out_trade_nos[1]);

        //return "/jsp/info.jsp";
        response.sendRedirect(request.getContextPath()+"/jsp/info.jsp");
    }
}